const Enum = require("../enum/index");
const { ERROR, SUCCESS } = Enum;

module.exports = class ApiResult {
  /**
   * 异常处理
   * @return {module.exports.ERROR|{code, message}|*}
   * @constructor
   */
  static ERROR() {
    let respError = ERROR;
    switch (arguments.length) {
      case 1: {
        const param = arguments[0];
        switch (typeof param) {
          case "object":
            respError = param;
            break;
          case "string":
          case "number":
            respError = { code: ERROR.code, message: param };
            break;
          default:
            throw new Error(
              `【错误的参数类型】value -> ${JSON.stringify(
                param
              )}，期待值[string, number, object]`
            );
        }
        break;
      }
      case 2: {
        const params = arguments;
        if (typeof params[0] !== "number") {
          throw new Error(
            `【错误的参数类型】value -> ${JSON.stringify(
              params[0]
            )}，期待值[number]`
          );
        }
        if (!["string", "number"].includes(typeof params[1])) {
          throw new Error(
            `【错误的参数类型】value -> ${JSON.stringify(
              params[1]
            )}，期待值[string, number]`
          );
        }
        respError = { code: params[0], message: params[1] };
        break;
      }
    }
    return respError;
  }

  /**
   * 成功处理
   * @return {module.exports.SUCCESS|{code, data, message}|*}
   * @constructor
   */
  static SUCCESS() {
    let respSuccess = SUCCESS;
    switch (arguments.length) {
      case 1: {
        const param = arguments[0];
        respSuccess = {
          code: SUCCESS.code,
          message: SUCCESS.message,
          data: param
        };
        break;
      }
      case 2: {
        const params = arguments;
        if (!["string", "number"].includes(typeof params[1])) {
          throw new Error(
            `【错误的参数类型】value -> ${JSON.stringify(
              params[1]
            )}，期待值[string, number]`
          );
        }
        respSuccess = {
          code: SUCCESS.code,
          data: params[0],
          message: params[1]
        };
        break;
      }
      case 3: {
        const params = arguments;
        if (typeof params[0] !== "number") {
          throw new Error(
            `【错误的参数类型】value -> ${JSON.stringify(
              params[0]
            )}，期待值[number]`
          );
        }
        if (!["string", "number"].includes(typeof params[2])) {
          throw new Error(
            `【错误的参数类型】value -> ${JSON.stringify(
              params[1]
            )}，期待值[string, number]`
          );
        }
        respSuccess = { code: params[0], data: params[1], message: params[2] };
      }
    }
    return respSuccess;
  }
};
